package com.shuqi.database.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import android.content.Context;
import android.text.TextUtils;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Constant;
import com.shuqi.database.dao.OrmBaseDao;
import com.shuqi.database.model.TxtCatalog;
import com.shuqi.model.bean.BookContentInfo;

/**
 * 
 * @author yaozhen
 * 
 */
public class TxtCatalogDao extends OrmBaseDao {

    private static TxtCatalogDao mInstance;

    private RuntimeExceptionDao<TxtCatalog, Integer> mDao = ShuqiDatabaseHelper.getHelper(
            ShuqiApplication.getContext()).getRuntimeExceptionDao(TxtCatalog.class);

    private TxtCatalogDao(Context context) {

    }

    public static synchronized TxtCatalogDao getInstance() {
        if (mInstance == null) {
            mInstance = new TxtCatalogDao(ShuqiApplication.getContext());
        }
        return mInstance;
    }

    public boolean isRunOld = false;// 7.3.8 某章节大小超过40K时，认为断章走20K的逻辑

    /**
     * 保存txtCatalogList 插入之前删除之前的数据
     * 
     * @return
     */
    public int saveTxtCatalogList(final List<BookContentInfo> list, final String filePath,
            final int fileLength) {
        Callable<Void> callble = new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                DeleteBuilder<TxtCatalog, Integer> deleteBuilder = mDao.deleteBuilder();
                deleteBuilder.where().eq("file_path", filePath);
                deleteBuilder.delete();
                int lastStartIndex = 0;
//                for (BookContentInfo info : list) {
//                    TxtCatalog txtCatalog = new TxtCatalog();
//                    if (info.getStartIndex() - lastStartIndex > Constant.READ_BYTEBUFFER_LENTH_40) {
//                        isRunOld = true;
//                    }
//                    txtCatalog.setChapterIndex(info.getStartIndex());
//
//                    txtCatalog.setChapterEndIndex(info.getEndIndex());
//                    txtCatalog.setFilePath(filePath);
//                    txtCatalog.setChapterName(info.getCurChapterName());
//                    mDao.create(txtCatalog);
//                    lastStartIndex = info.getStartIndex();
//                }
                for (int i = 0; i < list.size(); i++) {
                    TxtCatalog txtCatalog = new TxtCatalog();
                    if (list.get(i).getStartIndex() - lastStartIndex > Constant.READ_BYTEBUFFER_LENTH_40) {
                        isRunOld = true;
                    }
                    if (i == 0) {
                        if (list.get(i).getStartIndex() != 0) {
                            txtCatalog.setChapterIndex(0);
                        } else {
                            txtCatalog.setChapterIndex(list.get(i).getStartIndex());
                        }
                    } else {
                        txtCatalog.setChapterIndex(list.get(i).getStartIndex());
                    }
                    if (i == list.size() - 1) {
                        if (list.get(i).getEndIndex() == 0) {
                            txtCatalog.setChapterEndIndex(fileLength);
                        } else {
                            txtCatalog.setChapterEndIndex(list.get(i).getEndIndex());
                        }
                    } else {
                        txtCatalog.setChapterEndIndex(list.get(i).getEndIndex());
                    }
                    txtCatalog.setFilePath(filePath);
                    txtCatalog.setChapterName(list.get(i).getCurChapterName());
                    mDao.create(txtCatalog);
                    lastStartIndex = txtCatalog.getChapterIndex();
                }
                return null;
            }
        };
        try {
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 根据filepath 查询出目录list
     * 
     * @return
     */
    public List<BookContentInfo> getTxtCatalogListByFilePath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }

        QueryBuilder<TxtCatalog, Integer> queryBuilder = mDao.queryBuilder();
        try {
            queryBuilder.where().eq("file_path", filePath);
            List<TxtCatalog> list = queryBuilder.query();
            List<BookContentInfo> resultList = new ArrayList<BookContentInfo>();
            for (TxtCatalog txtCatalog : list) {
                BookContentInfo info = new BookContentInfo();
                info.setFliePath(txtCatalog.getFilePath());
                info.setStartIndex(txtCatalog.getChapterIndex());
                info.setEndIndex(txtCatalog.getChapterEndIndex());
                info.setCurChapterName(txtCatalog.getChapterName());
                resultList.add(info);
            }

            // for (int i = 0; i < resultList.size() - 1; i++) {
            // resultList.get(i).setEndIndex(resultList.get(i + 1).getStartIndex());
            // }
            return resultList;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据filepath删除章节
     * 
     * @param filePath
     * @return
     */
    public int deleteTxtCatalogByFilePath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return -1;
        }
        DeleteBuilder<TxtCatalog, Integer> deleteBuilder = mDao.deleteBuilder();
        try {
            deleteBuilder.where().eq("file_path", filePath);
            return deleteBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * 删除所有章节
     * 
     * @return
     */
    public int deleteAllTxtCatalog() {
        try {
            return mDao.deleteBuilder().delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return -1;
    }

}
